package com.flying.ouyu.net.handler;

import com.flying.client.network.IMsgHandler;
import com.flying.client.network.msg.ORMsg;
import com.flying.client.network.msg.OWMsg;
import com.flying.client.utils.Logger;
import com.flying.ouyu.net.MessageType;
import com.flying.ouyu.net.NetworkProxy;
import com.flying.ouyu.net.proto.OuyuProto.MessageStatus;
import com.flying.ouyu.net.proto.OuyuProto.Session;
import com.google.protobuf.InvalidProtocolBufferException;

import com.flying.ouyu.config.Config;

public class InitHandler implements IMsgHandler{
	private static final Logger logger = Logger.getLogger(InitHandler.class.getName());
	
	private static Object _instanceLocker = new Object();
	private static InitHandler _instance = null;
	
	public static InitHandler getInstance()
	{
		if (_instance != null)
			return _instance;
		
		synchronized(_instanceLocker)
		{
			if (_instance == null)
			{
				_instance = new InitHandler();
			}
			return _instance;
		}
	}
	
	private InitHandler(){}
	
	
	public void onMsg(ORMsg rMsg) {
		logger.debug("onMsg rMsg="+rMsg);
		
		try
		{
			int statusLen = rMsg.getMsgContent().readInt();
			
			MessageStatus status = MessageStatus.parseFrom(rMsg.getMsgContent().readBytes(statusLen).array());
			if (status.getMessageStatus() == MessageStatus.Status.FAILED)
			{
				//TODO:这里服务器返回错误状态嘛！！！！！
				return;
			}
			
			int sessionLen = rMsg.getMsgContent().readInt();
			
			Session session = Session.parseFrom(rMsg.getMsgContent().readBytes(sessionLen).array());;
			
			if (session != null)
			{
				logger.debug("sessionKey="+session.getSessionKey());
				//保存sessionkey
				Config.getInstance().setSesssionKey(session.getSessionKey());
			}
		}
		catch(InvalidProtocolBufferException e)
		{
			e.printStackTrace();
			throw new RuntimeException(e);
		}
	}

	public void sendMsg()
	{
		OWMsg msg = new OWMsg(MessageType.Init);
		NetworkProxy.getInstance().send(msg);
	}
}
